//
//  VPCommentInputBar.m
//  vidpioneer
//
//  Created by pcyang on 15/7/29.
//  Copyright (c) 2015年 tencent. All rights reserved.
//

#import "VPCommentInputBar.h"

#define TEXT_FIELD_TOP_PADDING       10
#define TEXT_FIELD_LEFT_PADDING      12

#define TEXT_CONTENT_TOP_PADDING       10
#define TEXT_CONTENT_LEFT_PADDING      14

#define TEXT_FIELD_TEXT_FONT_SIZE    15
#define TEXT_FIELD_NUMBER_OF_LINES   5
#define TEXT_FIELD_DEFAULT_HEIGHT    34

#define INPUT_VIEW_TOTAL_HEIGHT      TEXT_FIELD_DEFAULT_HEIGHT+2*TEXT_FIELD_TOP_PADDING

#define BUTTON_LEFT_PADDING          7


#define kInputCellButtonWidth        30
#define kInputCellButtonHeight       30

#define kSendButtonWidth 55
#define kRightPadding  10


#define EMOTIONBOARD_HEIGHT   216.0f        //表情面板高度

#define COUNT_LABEL_WIDTH       30
#define COUNT_LABEL_HEIGHT      20

#define QLAPPCONF_MomentCommentContentMaxCount 200



@class VPOverlayView;

@protocol VPOverlayViewDelegate <NSObject>
- (void)viewDidSwipe:(VPOverlayView *)swipeView;
@end

@interface VPOverlayView : UIView
@property(nonatomic,weak)id delegate;
@end


@implementation VPOverlayView

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    if (_delegate && [_delegate respondsToSelector:@selector(viewDidSwipe:)]) {
        [_delegate viewDidSwipe:self];
    }
}

@end

@implementation QLMomentTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.isHideCursorOrNot = NO;
        self.isSwitchingKeyBoardOrNot = YES;
    }
    return self;
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (self.isHideCursorOrNot) {
        return NO;
    }
    return [super canPerformAction:action withSender:sender];
}

//Disables caret
- (CGRect)caretRectForPosition:(UITextPosition *)position
{
    if (!self.isHideCursorOrNot) {
        return [super caretRectForPosition:position];
    }else{
        return CGRectZero;
    }
}

@end

@interface VPCommentInputBar()<UITextViewDelegate,VPOverlayViewDelegate>
@property (nonatomic, strong) UIButton * faceSendButton;
@property (nonatomic, strong) UIButton *keyboardButton;
@property(nonatomic, strong)  UIButton * callSystemKbBtn;

@property (nonatomic, strong) QLMomentTextView *textView;
@property (nonatomic, strong) UILabel *tipsLabel;
@property (nonatomic, strong) UILabel *countLabel;

@property (nonatomic, assign) UIView *mainView;
@property (nonatomic, strong) UIView *toolView;
@property (nonatomic, strong) UIView *thumbnailView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIImageView *textBgView;
@property (nonatomic, strong) UIView *rightView;
@property (nonatomic, strong)VPOverlayView* overlayView;

@property (nonatomic, assign) CGRect keyboardEndRect;
@property (nonatomic, assign) CGSize lastSize;
@property (nonatomic, assign) UIEdgeInsets textFieldInsets;
@property (nonatomic, assign) UIEdgeInsets textContentInsets;
@property (nonatomic, assign) CGFloat textFieldDefaultHeight;

@property (nonatomic, assign) BOOL isSwitchingKeyBoard;
@property(nonatomic, assign)  BOOL isShouldChangeFlag;
@end

@implementation VPCommentInputBar

+(void)showInputBarAddedTo:(UIView*)view delegate:(id<VPCommentInputBarDelegate>)delegate text:(NSString*)text
{
    [[self class] showInputBarAddedTo:view delegate:delegate placeHolderText:nil];
    VPCommentInputBar *inputView = [self sharedInstance];
    inputView.tipsLabel.hidden = YES;
    [inputView.textView setText:text];
    
}
+(void)showInputBarAddedTo:(UIView*)view delegate:(id<VPCommentInputBarDelegate>)delegate placeHolderText:(NSString*)placeHolderText
{

    VPCommentInputBar *inputView = [self sharedInstance];
    
    BOOL flag = YES;
    if (delegate && [delegate respondsToSelector:@selector(commentInputBarShouldBeginEditing:)]) {
        flag = [delegate commentInputBarShouldBeginEditing:inputView];
    }
    
    if (!flag) 
        return;
    
    inputView.delegate = delegate;
    [inputView setMainView:view];
    

    inputView.tipsLabel.text = placeHolderText;
    
    [inputView resetTextViewHeight:NO text:@""];
    [inputView resetTipsAndCountLabel];
    
    if (![inputView.textView isFirstResponder]) {
        inputView.faceSendButton.hidden = NO;
        inputView.keyboardButton.hidden = YES;
        
        if (inputView.textView.inputView) {
            inputView.textView.inputView = nil;
        }
        [inputView.textView becomeFirstResponder];
    }
    
//    if (inputView.faceSendButton.tag == KeyBoardType_Only_Symbol) {
//        inputView.faceSendButton.hidden = YES;
//        inputView.keyboardButton.hidden = YES;
//    }

}
+ (void)dismiss
{
    VPCommentInputBar *inputView = [self sharedInstance];
    [inputView setMainView:nil];
    inputView.delegate = nil;
    
    inputView.maxLength = 0;
}

+(void)clearText
{
    VPCommentInputBar *inputView = [self sharedInstance];
    [inputView.textView setText:@""];

}
+ (BOOL)isShowed
{
    return nil != [self sharedInstance].superview;
}

+ (VPCommentInputBar *)sharedInstance
{
    static VPCommentInputBar *inputView = nil;
    if (inputView == nil){
        @synchronized(self) {
            if (inputView == nil){
                CGSize size = [VPCommentInputBar viewSize];
                inputView = [[VPCommentInputBar alloc] initWithFrame:CGRectMake(0, kScreenHeight-size.height, size.width, size.height)];
            }
        }
    }
    return inputView;
}

+ (CGSize)viewSize
{
    return CGSizeMake(kScreenWidth, INPUT_VIEW_TOTAL_HEIGHT);
}

- (CGSize)inputViewSize
{
 
    if (nil != _mainView) {
        return CGSizeMake(_mainView.width, _textFieldDefaultHeight+2*_textFieldInsets.top); //by snowywu
    }
    
    return self.bounds.size;
}

- (void)setMainView:(UIView *)mainView
{
    if (nil == mainView) {
        
        if (_overlayView) {
            [_overlayView removeFromSuperview];
            _overlayView = nil;
        }
        
        _mainView = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        if (nil != self.superview) {
            [self.textView resignFirstResponder];
            [self removeFromSuperview];
        }
        return;
    }
    
    _mainView = mainView;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];

    [[VPCommentInputBar sharedInstance] addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

    CGSize size = [self inputViewSize];
    // modified by tencent:jiachunke(20141210)
    size.height += _toolView.height;
    
    CGAffineTransform tempT1 = CGAffineTransformIdentity;
    tempT1 = CGAffineTransformMakeRotation(M_PI_2);
    CGAffineTransform tempT2 = CGAffineTransformIdentity;
    tempT2 = CGAffineTransformMakeRotation(-M_PI_2);
    if (CGAffineTransformEqualToTransform(tempT1, mainView.transform) ||
        CGAffineTransformEqualToTransform(tempT2, mainView.transform)) {
        size.width = mainView.height;
    } else {
        size.width = mainView.width;
    }
    
    self.frame = CGRectMake(0, _mainView.height-size.height, size.width, size.height);
    
    [_mainView addSubview:self];
    [self showOverlayView];
    
    [self layoutAtOnce];
}

-(void)showOverlayView
{
    if (_overlayView) {
        [_overlayView removeFromSuperview];
        _overlayView = nil;
    }

    _overlayView = [[VPOverlayView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - self.height)];
    _overlayView.delegate = self;
    [_mainView addSubview:_overlayView];
//    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:[VPCommentInputBar class] action:@selector(dismiss)];
//    [_overlayView addGestureRecognizer:tapGestureRecognizer];

}

- (void)viewDidSwipe:(VPOverlayView *)swipeView
{
    [self dismissOverlayView];
}

-(void)dismissOverlayView
{
    if (_overlayView) {
        [_overlayView removeFromSuperview];
        _overlayView = nil;
    }
    
    [VPCommentInputBar dismiss];
}

- (void)setToolView:(UIView *)toolView
{
    if (_toolView == toolView) {
        return;
    }
    
    if (nil != _toolView) {
        [_toolView removeFromSuperview];
        _toolView = nil;
    }
    
    if (nil != toolView) {
        _toolView = toolView;
    }
    
    [self addSubview:_toolView];
}

- (void)setThumbnailView:(UIView *)thumbnailView
{
    if (_thumbnailView == thumbnailView) {
        return;
    }
    
    if (nil != _thumbnailView) {
        [_thumbnailView removeFromSuperview];
        _thumbnailView = nil;
    }
    
    _thumbnailView = thumbnailView;

    [self addSubview:_thumbnailView];
}

- (void)setRightView:(UIView *)rightView
{
    if (_rightView == rightView) {
        return;
    }
    
    if (nil != _rightView) {
        [_rightView removeFromSuperview];
        _rightView = nil;
    }
    
    _rightView = rightView;

    
    [self addSubview:_rightView];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        // modified by tencent:jiachunke(20141013)
        CGSize size = frame.size;
        
        // 3.8.1支持灵活控制输入框size，tencent:jiachunke(20150303)
        self.textFieldInsets = UIEdgeInsetsMake(TEXT_FIELD_TOP_PADDING, TEXT_FIELD_LEFT_PADDING, TEXT_FIELD_TOP_PADDING, TEXT_FIELD_LEFT_PADDING);
        self.textContentInsets = UIEdgeInsetsMake(TEXT_CONTENT_TOP_PADDING, TEXT_CONTENT_LEFT_PADDING, TEXT_CONTENT_TOP_PADDING, TEXT_CONTENT_LEFT_PADDING);
        self.textFieldDefaultHeight = TEXT_FIELD_DEFAULT_HEIGHT;
        
        _bgView = [[UIView alloc] initWithFrame:self.bounds];
        _bgView.backgroundColor =RGB(0xff, 0xff, 0xff);
        
        UIView* topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _bgView.width, 0.5f)];
        topLineView.backgroundColor = RGB(0xef, 0xef, 0xef);
        [_bgView addSubview:topLineView];
        
        [self addSubview:_bgView];
        
        self.faceSendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _faceSendButton.backgroundColor = [UIColor clearColor];
        _faceSendButton.frame = CGRectMake(BUTTON_LEFT_PADDING, _textFieldInsets.top+2, 0, kInputCellButtonHeight);
        [_faceSendButton setImage:LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle,@"btn_details_emoji_nor.png") forState:UIControlStateNormal];
        [_faceSendButton setImage:LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle,@"btn_details_emoji_press.png") forState:UIControlStateHighlighted];
        [_faceSendButton addTarget:self action:@selector(didClickEmojiBtn:) forControlEvents:UIControlEventTouchUpInside];
        _faceSendButton.hidden = NO;
        [self addSubview:_faceSendButton];
        
//        self.keyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _keyboardButton.backgroundColor = [UIColor clearColor];
//        _keyboardButton.frame = CGRectMake(BUTTON_LEFT_PADDING, _textFieldInsets.top+2, kInputCellButtonWidth, kInputCellButtonHeight);
//        [_keyboardButton setImage:LOAD_IMAGE_USE_CACHE_INBUNDLE(CommentBundle,@"btn_details_keyboard_nor.png") forState:UIControlStateNormal];
//        [_keyboardButton setImage:LOAD_IMAGE_USE_CACHE_INBUNDLE(CommentBundle,@"btn_details_keyboard_press.png") forState:UIControlStateHighlighted];
//        [_keyboardButton addTarget:self action:@selector(didClickKeyBoardBtn:) forControlEvents:UIControlEventTouchUpInside];
//        _keyboardButton.hidden = YES;
//        [self addSubview:_keyboardButton];
//        
        _textBgView = [[UIImageView alloc] initWithImage:[LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle,@"bg_inputbox.png") stretchableImageWithLeftCapWidth:5 topCapHeight:16]];
        _textBgView.frame = CGRectMake(_faceSendButton.right+BUTTON_LEFT_PADDING, _textFieldInsets.top, size.width - (_faceSendButton.right + BUTTON_LEFT_PADDING + kRightPadding), _textFieldDefaultHeight);
        [self addSubview:_textBgView];
        
        _textView = [[QLMomentTextView alloc] initWithFrame:CGRectMake(_faceSendButton.right+BUTTON_LEFT_PADDING, _textContentInsets.top,  _textBgView.width - _textContentInsets.left, size.height-2*_textContentInsets.top)];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.font = [UIFont systemFontOfSize:TEXT_FIELD_TEXT_FONT_SIZE];
        _textView.returnKeyType = UIReturnKeySend;
        // 由于中文键盘可以支持使用联想输入，输入框也支持复制粘贴，所以暂时关闭自动调整属性，tencent:jiachunke(20141106)
        //_textView.enablesReturnKeyAutomatically = YES;
        _textView.delegate = self;
        [self addSubview:_textView];
        
//        UIButton* sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        sendButton.backgroundColor = [UIColor clearColor];
//        sendButton.frame = CGRectMake(_textView.right + 5, _textFieldInsets.top+1, kSendButtonWidth, 30);
//        [sendButton setBackgroundImage:LOAD_IMAGE_USE_CACHE_INBUNDLE(CommentBundle,@"bt_send.png") forState:UIControlStateNormal];
//        [sendButton addTarget:self action:@selector(didPressSendButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        [sendButton setTitleColor:RGB(0xff, 0xff, 0xff) forState:UIControlStateNormal];
//        [sendButton setTitle:@"发送" forState:UIControlStateNormal];
//        sendButton.titleLabel.font = [UIFont systemFontOfSize:12.0];
//        [self addSubview:sendButton];
        
        self.callSystemKbBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_callSystemKbBtn addTarget:self action:@selector(handleSingleTap) forControlEvents:UIControlEventTouchDown];
        [_callSystemKbBtn setBackgroundColor:[UIColor clearColor]];
        [_textView addSubview:_callSystemKbBtn];
        _callSystemKbBtn.hidden = YES;
        
        self.tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(_faceSendButton.right+(_textContentInsets.left+6), _textFieldInsets.top, 180, _textFieldDefaultHeight)];
        if (![UIDevice isIOS7OrLatter]) {
            _tipsLabel.frame = CGRectMake(_faceSendButton.right+(_textContentInsets.left+12), _textFieldInsets.top, 180, _textFieldDefaultHeight);
        }
        _tipsLabel.backgroundColor = [UIColor clearColor];
        _tipsLabel.font = _textView.font;
        _tipsLabel.textColor = [UIColor colorWithRed:(0x89)/255.f green:(0x89)/255.f blue:(0x89)/255.f alpha:1];
        _tipsLabel.text = (@"说说...");
        [self addSubview:_tipsLabel];
        
        self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(_textView.left+5, _textView.bottom-COUNT_LABEL_HEIGHT, COUNT_LABEL_WIDTH, COUNT_LABEL_HEIGHT)];
        _countLabel.backgroundColor = [UIColor clearColor];
        _countLabel.textAlignment = NSTextAlignmentCenter;
        _countLabel.font = [UIFont italicSystemFontOfSize:13];
        _countLabel.textColor = [UIColor redColor];
        _countLabel.hidden = YES;
        [self addSubview:_countLabel];
        
        self.keyboardEndRect = self.frame;
        
        self.lastSize = CGSizeZero;
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

- (void)layoutAtOnce
{
    CGSize size = [self inputViewSize];
    if (self.lastSize.height != 0 && size.height < self.lastSize.height - self.toolView.size.height) {
        size = CGSizeMake(size.width, self.lastSize.height - self.toolView.size.height);
    }
    
    _bgView.frame = CGRectMake(0, 0, size.width, size.height + _toolView.height);
    self.frame = CGRectMake(self.origin.x, self.origin.y, size.width, size.height + _toolView.height);
    
    [self layoutTextView];
    [self layoutDecorativeViews];
}

- (void)layoutTextView
{
    CGSize size = [self inputViewSize];
    if (self.lastSize.height != 0 && size.height < self.lastSize.height - self.toolView.size.height) {
        size = CGSizeMake(size.width, self.lastSize.height - self.toolView.size.height);
    }
    
   // CGFloat rightPadding = (_rightView.width>0)?_textFieldInsets.left:0;
    CGFloat leftPadding = 0;
    
    _thumbnailView.frame = CGRectMake(_textFieldInsets.left, (size.height - _thumbnailView.height)/2, _thumbnailView.width, _thumbnailView.height);
    
    CGFloat textViewOrgX = (_thumbnailView.width>0)?_thumbnailView.right+leftPadding:_textContentInsets.left;
    if (_faceSendButton.tag ==  KeyBoardType_Only_Symbol) {
        _textView.frame = CGRectMake(textViewOrgX, _textContentInsets.top, _textBgView.width - _textContentInsets.left, size.height-2*_textContentInsets.top);
    }else{
        _textView.frame = CGRectMake(_faceSendButton.right+_textFieldInsets.left, _textContentInsets.top, _textBgView.width - _textContentInsets.left, size.height-2*_textContentInsets.top);
    }
    
    //self.textView.contentSize = _textView.frame.size;
    _callSystemKbBtn.size = self.textView.contentSize;
}

- (void)layoutDecorativeViews
{
    CGSize size = [self inputViewSize];
    CGFloat rightPadding = (_rightView.width>0)?_textFieldInsets.left:0;
    CGFloat leftPadding = 0;
    
    CGFloat textBgViewOrgX = (_thumbnailView.width>0)?_thumbnailView.right+leftPadding:_textContentInsets.left;
    if (self.lastSize.height != 0 && size.height < self.lastSize.height - self.toolView.size.height) {
        size = CGSizeMake(size.width, self.lastSize.height - self.toolView.size.height);
    }
    
    if (_faceSendButton.tag == KeyBoardType_Only_Symbol) {
       // _textBgView.frame = CGRectMake(textBgViewOrgX, _textFieldInsets.top,  size.width - (_faceSendButton.right + BUTTON_LEFT_PADDING + kRightPadding), size.height-2*_textFieldInsets.top);
        
        _textBgView.height =  size.height-2*_textFieldInsets.top;
        
        _tipsLabel.frame = CGRectMake(textBgViewOrgX+6, _textFieldInsets.top, 180, _textFieldDefaultHeight);
        if (![UIDevice isIOS7OrLatter]) {
            _tipsLabel.frame = CGRectMake(textBgViewOrgX+12, _textFieldInsets.top, 180, _textFieldDefaultHeight);
        }
    }else{
       // _textBgView.frame = CGRectMake(_faceSendButton.right+_textFieldInsets.left, _textFieldInsets.top,  size.width - (_faceSendButton.right + BUTTON_LEFT_PADDING + kRightPadding), size.height-2*_textFieldInsets.top);
        
         _textBgView.height =  size.height-2*_textFieldInsets.top;
        
        _tipsLabel.frame = CGRectMake(_faceSendButton.right+(_textContentInsets.left+6), _textFieldInsets.top, 180, _textFieldDefaultHeight);
        if (![UIDevice isIOS7OrLatter]) {
            _tipsLabel.frame = CGRectMake(_faceSendButton.right+(_textContentInsets.left+12), _textFieldInsets.top, 180, _textFieldDefaultHeight);
        }
    }
    _countLabel.frame = CGRectMake(_textView.right-COUNT_LABEL_WIDTH, _textView.bottom-COUNT_LABEL_HEIGHT, COUNT_LABEL_WIDTH, COUNT_LABEL_HEIGHT);
    
    // modified by tencent:jiachunke(20141210)
    _toolView.frame = CGRectMake(0, size.height, _toolView.width, _toolView.height);
    
    _rightView.frame = CGRectMake(_textBgView.right+rightPadding, (self.height-_rightView.height)/2, _rightView.width, _rightView.height);
}

#define NSUInteger2Int(integer)	[@(integer) intValue]

- (NSUInteger)getBlogCountWords:(NSString *)text
{
    int i, n = NSUInteger2Int([text length]), l = 0, a = 0, b = 0;
    unichar c;
    
    for(i = 0; i < n; i++){
        c = [text characterAtIndex:i];
        
        if(isblank(c)){
            b++;
        }else if(isascii(c)){
            a++;
        }else{
            l++;
        }
    }
    
    if(a==0 && l==0) return 0;
    
    return l+(int)ceilf((float)(a+b)/2.0);
}

- (int)getNumOfLines:(NSString *)text
{
    int numOfLines = 0;
    if (0 < [text length]) {
        CGFloat width = _textView.bounds.size.width-10;
        if (![UIDevice isIOS7OrLatter]) {
            // iOS5/6的文字边距不同，要特别reset下，tencent:jiachunke(20140515)
            width = _textView.bounds.size.width-16;
        }
        CGSize textSize = [text sizeWithFont:_textView.font constrainedToSize:CGSizeMake(width, 9999)];
        numOfLines = ceilf(textSize.height/_textView.font.lineHeight);
    }
    return numOfLines;
}

- (CGFloat)getTextHeight:(int)numOfLines
{
    CGFloat textHeight = 0;
    
    // 由于content size的计算问题，两行起_textFieldDefaultHeight还是得大于默认的高度，否则最后一行可能展示不全，tencent:jiachunke(20150424)
    CGFloat tempHeight = _textFieldDefaultHeight>TEXT_FIELD_DEFAULT_HEIGHT ? _textFieldDefaultHeight : TEXT_FIELD_DEFAULT_HEIGHT;
    switch (numOfLines) {
        case 0:
        case 1:
            textHeight = _textFieldDefaultHeight;
            break;
        case 2:
            textHeight = tempHeight+(_textView.font.lineHeight);
            break;
        case 3:
            textHeight = tempHeight+2*(_textView.font.lineHeight);
            break;
        case 4:
            textHeight = tempHeight+3*(_textView.font.lineHeight);
            break;
        case 5:
        default:
            textHeight = tempHeight+4*(_textView.font.lineHeight);
            break;
    }
    return textHeight;
}

- (NSString *)getTextContent
{
    return [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (CGRect)getViewRect
{
    if ([VPCommentInputBar isShowed]) {
        return self.frame;
    }
    return CGRectZero;
}

- (CGRect)getViewAndKeyboardRect
{
    if ([VPCommentInputBar isShowed]) {
        return CGRectMake(self.origin.x, self.origin.y, self.width, self.height+self.keyboardEndRect.size.height);
    }
    return CGRectZero;
}

- (void)resetTipsAndCountLabel
{
    NSUInteger length = [self.textView.text length];
    if (0 == length) {
        self.tipsLabel.hidden = NO;
    } else {
        self.tipsLabel.hidden = YES;
    }
    
    NSString *textContent = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSUInteger maxLength = 0;
    
    if (_maxLength > 0) {
        maxLength = _maxLength;
    }
    else
        maxLength = QLAPPCONF_MomentCommentContentMaxCount;
    
        length = [self getBlogCountWords:textContent];
    
    
    if (maxLength < length) {
        self.countLabel.hidden = NO;
        self.countLabel.text = [NSString stringWithFormat:@"-%tu", length-maxLength];
        
        [SDAlertManagement showNormalErrorAlert:@"超出的部分会被截断呦~"];

    } else {
        self.countLabel.hidden = YES;
    }
}

- (void)resetViewFrameWithKeyboardRect:(CGRect)keyboardEndRect height:(CGFloat)height numberOfLines:(int)numberOfLines
{
    // 3.7.1在搜狗第三方输入法场景有些小bug，调整下，subviews直接layout，tencent:jiachunke(20141118)
    //if (self.frame.size.height != height) {
    //    [self setNeedsLayout];
    //}
    
    BOOL heightIsChanged = NO;
    if (self.frame.size.height != height) {
        heightIsChanged = YES;
    }
    
//    // 支持外部拉起statusbar展示的场景，tencent:jiachunke(20140626)
    CGFloat barHeight = 0;
//    if ([QLStatusBar isShowed]) {
//        QLStatusBar *bar = [QLStatusBar sharedInstance];
//        if ([UIDevice isIOS7OrLatter]) {
//            barHeight = bar.height-[UIApplication sharedApplication].statusBarFrame.size.height;
//        } else {
//            barHeight = bar.height;
//        }
//    }
    if (keyboardEndRect.size.width > keyboardEndRect.size.height) {
        self.frame = CGRectMake(0, keyboardEndRect.origin.y-height-barHeight, self.width, height);
    } else {
        self.frame = CGRectMake(0, keyboardEndRect.origin.x-height-barHeight, self.width, height);
    }
    
    self.keyboardEndRect = keyboardEndRect;
    
    self.lastSize = self.size;
    
    if (heightIsChanged) {
        [self layoutAtOnce];
    }
    
    //在frame正确设置完之后再滚动，否则会出现粘贴大段文字后，光标定位到第二行，然后下方都是空白的情况 Norcy(20150822)
    //非0判断是为了让除了resetTextViewHeight方法之外的方法不要走到这里，遵循原有的逻辑
    if (numberOfLines != 0)
        [self textViewScrollToVisibel:numberOfLines];
    
    _overlayView.bottom = self.top;

}

- (void)resetTextViewHeight:(BOOL)animation text:(NSString *)text {
    
    int numOfLines = [self getNumOfLines:text];
    if (0 == numOfLines) {numOfLines = 1;}
    CGFloat tempHeight = [self getTextHeight:numOfLines];
    

    CGFloat height = tempHeight+_textFieldInsets.top+_textFieldInsets.bottom;
    height += _toolView.height;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (animation) {
            __block VPCommentInputBar *blockSelf = self;
            [UIView animateWithDuration:0.3
                             animations:^{
                                 [blockSelf resetViewFrameWithKeyboardRect:blockSelf.keyboardEndRect height:height numberOfLines:numOfLines];
                             } completion:^(BOOL finished) {
                                 // do nothing
                             }];
        } else {
            [self resetViewFrameWithKeyboardRect:self.keyboardEndRect height:height numberOfLines:numOfLines];
        }
    });
}

- (void)didClickEmojiBtn:(id)sender{
    _faceSendButton.hidden = YES;
    _keyboardButton.hidden = NO;
    _isSwitchingKeyBoard = YES;
    
    [self showEmotionBoard];
    
    if ([self.delegate respondsToSelector:@selector(commentInputBarDidPressEmojiButton:)]) {
        [self.delegate commentInputBarDidPressEmojiButton:self];
    }
}

- (void)didClickKeyBoardBtn:(id)sender{
    _faceSendButton.hidden = NO;
    _keyboardButton.hidden = YES;
    _isSwitchingKeyBoard = YES;
    
    [self showSystemKeyBoard];
    
    if ([self.delegate respondsToSelector:@selector(commentInputBarDidPressKeyBoardButton:)]) {
        [self.delegate commentInputBarDidPressKeyBoardButton:self];
    }
}

-(void)handleSingleTap{
    if (!self.textView.isSwitchingKeyBoardOrNot && self.textView.isHideCursorOrNot) {
        [self showSystemBoardInTextView:self.textView];
    }
}

- (void)showSystemKeyBoard{
    self.textView.isHideCursorOrNot = NO;
    self.textView.isSwitchingKeyBoardOrNot = YES;
    [self setInputViewToView:nil];
    _callSystemKbBtn.hidden = YES;
    _isSwitchingKeyBoard = NO;
}

- (void)showEmotionBoard{
//    [[QLEmojiFaceKeyBoard getInstance] setEditViewValue:NO horizontal:NO];
//    [[QLEmojiFaceKeyBoard getInstance] setBoardViewDelegate:self];
//    
//    self.textView.isHideCursorOrNot = YES;
//    self.textView.isSwitchingKeyBoardOrNot = YES;
//    [self setInputViewToView:[QLEmojiFaceKeyBoard getInstance]];
//    _callSystemKbBtn.hidden = NO;
//    _isSwitchingKeyBoard = NO;
}

- (void)setInputViewToView:(UIView *)view {
    if (self.textView.isFirstResponder) {
        [self.textView resignFirstResponder];
        self.textView.inputView = view;
        [self.textView becomeFirstResponder];
    }else{
        self.textView.inputView = view;
    }
    self.textView.isSwitchingKeyBoardOrNot = NO;
}

- (UIView *)findKeyboard
{
    UIView *keyboardView = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in [windows reverseObjectEnumerator]) //逆序效率更高，因为键盘总在上方
    {
        keyboardView = [self findKeyboardInView:window];
        if (keyboardView)
        {
            return keyboardView;
        }
    }
    return nil;
}

- (UIView *)findKeyboardInView:(UIView *)view
{
    for (UIView *subView in [view subviews])
    {
        if (strstr(object_getClassName(subView), "UIKeyboard"))
        {
            return subView;
        }
        else
        {
            UIView *tempView = [self findKeyboardInView:subView];
            if (tempView)
            {
                return tempView;
            }
        }
    }
    return nil;
}

- (void)didPressSendButtonAction:(id)sender
{
    // 去掉前后空格,空行，tencent:jiachunke(20140701)
    
    NSString *textContent = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    // 支持弹幕的字数独立控制，tencent:jiachunke(20140626)
    NSUInteger maxLength = 0;
    NSUInteger length = 0;
    
    if (_maxLength > 0) {
        maxLength = _maxLength;
    }
    else
        maxLength = QLAPPCONF_MomentCommentContentMaxCount;
    
    length = [self getBlogCountWords:textContent];
    if (maxLength < length) {
//        NSString *promptText = [NSString stringWithFormat:(@"字数最多可输入%lu字，已超过%lu字"), (unsigned long)maxLength, (length-maxLength)];
        
        NSMutableString * inputString = [NSMutableString stringWithString:self.textView.text];
        
        NSRange stringRange = {0,maxLength};
        self.textView.text = [inputString substringWithRange:stringRange];
        
      //  [VPAlertManagement showNormalErrorAlert:@"超出的部分会被截断呦~"];
        
    } else if (0 == length) {
        
       [SDAlertManagement showNormalErrorAlert:@"内容不能为空"];
       // [_textView resignFirstResponder];
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(commentInputBarDidPressSendButton:)]) {
        [self.delegate commentInputBarDidPressSendButton:self];
    }
    [_textView resignFirstResponder];
    
    [VPCommentInputBar clearText];
    
    self.lastSize = CGSizeZero;
}

- (void)setFaceEnabled:(BOOL)flag
{
    if (flag) {
        self.faceSendButton.tag = KeyBoardType_Has_Face;
        self.faceSendButton.hidden = NO;
        self.keyboardButton.hidden = YES;
    } else {
        self.faceSendButton.tag = KeyBoardType_Only_Symbol;
        self.faceSendButton.hidden = YES;
        self.keyboardButton.hidden = YES;
    }
}

#pragma mark - KeyboardNotification

- (void)keyboardWillShowNotification:(NSNotification *)not
{
    if (nil != self.mainView) {
        NSDictionary *userInfo = [not userInfo];
        /* 根据通知传递过来的用户信息，分别获取动画类型，动画持续时间和键盘的框架*/
        NSValue *animationCurveObject = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
        NSValue *animationDurationObject = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
        NSValue *keyboardBeginRectObject = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
        NSValue *keyboardEndRectObject = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        NSUInteger animationCurve = 0;
        double animationDuration = 0.0f;
        CGRect keyboardBeginRect = CGRectZero;
        CGRect keyboardEndRect = CGRectZero;
        
        [animationCurveObject getValue:&animationCurve];
        [animationDurationObject getValue:&animationDuration];
        [keyboardBeginRectObject getValue:&keyboardBeginRect];
        [keyboardEndRectObject getValue:&keyboardEndRect];
        
        BOOL isShowingSystemBoard = NO;
        if (keyboardBeginRect.origin.x < 0 || keyboardBeginRect.origin.x >= [UIScreen mainScreen].bounds.size.width ||
            keyboardBeginRect.origin.y < 0 || keyboardBeginRect.origin.y >= [UIScreen mainScreen].bounds.size.height) {
            isShowingSystemBoard = YES;
        }
        if (!isShowingSystemBoard || _isSwitchingKeyBoard) {
            // 切换键盘不用动画效果，tencent:jiachunke(20140312)
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            /*这里就是之前提到的，要将键盘的框架转换成当前的坐标系，因为键盘框架是不考虑设备方向的。*/
            keyboardEndRect = [self.mainView convertRect:keyboardEndRect fromView:window];
            /*这里获取的是键盘框架和当前window交叉（或重叠）的空间，也是CGRect。*/
            //CGRect intersectionOfKeyboardRectAndWindowRect = CGRectIntersection(window.frame, keyboardEndRect);
            
            [self resetViewFrameWithKeyboardRect:keyboardEndRect height:self.height numberOfLines:0];
        } else {
            
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            
            keyboardBeginRect = [self.mainView convertRect:keyboardBeginRect fromView:window];
            
            if (keyboardBeginRect.size.width > keyboardBeginRect.size.height) {
                self.frame = CGRectMake(0, abs((int)keyboardBeginRect.origin.y)-self.height, self.width, self.height);
            } else {
                self.frame = CGRectMake(0, abs((int)keyboardBeginRect.origin.x)-self.height, self.width, self.height);
            }
            
            [UIView beginAnimations:@"ShowMomentInputView" context:NULL];
            [UIView setAnimationCurve:animationCurve];
            [UIView setAnimationDuration:animationDuration];
            
            /*这里就是之前提到的，要将键盘的框架转换成当前的坐标系，因为键盘框架是不考虑设备方向的。*/
            keyboardEndRect = [self.mainView convertRect:keyboardEndRect fromView:window];
            /*这里获取的是键盘框架和当前window交叉（或重叠）的空间，也是CGRect。*/
            //CGRect intersectionOfKeyboardRectAndWindowRect = CGRectIntersection(window.frame, keyboardEndRect);
            
            [self resetViewFrameWithKeyboardRect:keyboardEndRect height:self.height  numberOfLines:0];
            
            [UIView commitAnimations];
        }
    }
}

- (void)keyboardDidShowNotification:(NSNotification *)not
{
    // do nothing
}

- (void)keyboardWillHideNotification:(NSNotification *)not
{
    if (nil != self.mainView && !_isSwitchingKeyBoard) {
        NSDictionary *userInfo = [not userInfo];
        /* 根据通知传递过来的用户信息，分别获取动画类型，动画持续时间和键盘的框架*/
        NSValue *animationCurveObject = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
        NSValue *animationDurationObject = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
        NSValue *keyboardBeginRectObject = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
        NSValue *keyboardEndRectObject = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        NSUInteger animationCurve = 0;
        double animationDuration = 0.0f;
        CGRect keyboardBeginRect = CGRectZero;
        CGRect keyboardEndRect = CGRectZero;
        
        [animationCurveObject getValue:&animationCurve];
        [animationDurationObject getValue:&animationDuration];
        [keyboardBeginRectObject getValue:&keyboardBeginRect];
        [keyboardEndRectObject getValue:&keyboardEndRect];
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        
        keyboardBeginRect = [self.mainView convertRect:keyboardBeginRect fromView:window];
        if (keyboardBeginRect.size.width > keyboardBeginRect.size.height) {
            self.frame = CGRectMake(0, keyboardBeginRect.origin.y-self.height, self.width, self.height);
        } else {
            self.frame = CGRectMake(0, keyboardBeginRect.origin.x-self.height, self.width, self.height);
        }
        
        [UIView beginAnimations:@"HideMomentInputView" context:NULL];
        [UIView setAnimationCurve:animationCurve];
        [UIView setAnimationDuration:animationDuration];
        
        //UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        /*这里就是之前提到的，要将键盘的框架转换成当前的坐标系，因为键盘框架是不考虑设备方向的。*/
        keyboardEndRect = [self.mainView convertRect:keyboardEndRect fromView:window];
        /*这里获取的是键盘框架和当前window交叉（或重叠）的空间，也是CGRect。*/
        //CGRect intersectionOfKeyboardRectAndWindowRect = CGRectIntersection(window.frame, keyboardEndRect);
        
        [self resetViewFrameWithKeyboardRect:keyboardEndRect height:self.height numberOfLines:0];
        
        [UIView commitAnimations];
    }
}

- (void)keyboardDidHideNotification:(NSNotification *)not
{
    // do nothing
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (0 == [textView.text length]) {
        self.tipsLabel.hidden = NO;
    } else {
        self.tipsLabel.hidden = YES;
    }
    
    if (!_isSwitchingKeyBoard) {
        [self removeFromSuperview];
        
        
        if ([self.delegate respondsToSelector:@selector(commentInputBarDidDismiss:)]) {
            [self.delegate commentInputBarDidDismiss:self];
        }
        
        [VPCommentInputBar clearText];

        self.mainView = nil;
        self.delegate = nil;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    _isShouldChangeFlag = YES;
    
    if ([text isEqualToString:@"\n"]) {
        [self didPressSendButtonAction:nil];
        return NO;
    }
    else if ([text length] == 0) {
        if (range.length > 1) {
            return YES;
        } else {
          //  if ([self backSpaceString])
           // {
            //    return NO;
            //}
            return YES;
        }
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self resetTipsAndCountLabel];
    
    [self resetTextViewHeight:YES text:self.textView.text];
    
    _isShouldChangeFlag = NO;
    
    
    if ([self.delegate respondsToSelector:@selector(commentInputBar:textViewDidChange:)]) {
        [self.delegate commentInputBar:self textViewDidChange:textView];
    }
}


- (UITextRange*)cutText:(NSString * )string{
    __block NSUInteger composedCharacterLength = 0;
    [string enumerateSubstringsInRange:NSMakeRange(0, string.length)
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
                                composedCharacterLength++;
                            }];
    UITextRange *rangeToDelete = [self.textView textRangeFromPosition:[self.textView positionFromPosition:self.textView.selectedTextRange.start offset:-composedCharacterLength] toPosition:self.textView.selectedTextRange.start];
    return rangeToDelete;
}

- (void)replaceTextInRange:(UITextRange *)range withText:(NSString *)text {
    if (range) {
        NSRange trange = [self nsrangeInTextRange:range];
        
        NSMutableString * inputString = [NSMutableString stringWithString:self.textView.text];
        
        if ([text length]== 0) {//删除
            if (trange.location!=NSNotFound) {
                
                [inputString replaceCharactersInRange:trange withString:text];
                self.textView.text = inputString;
                self.textView.selectedRange = NSMakeRange(trange.location, 0);
                // added by tencent:jiachunke(20141127)
                [self.textView scrollRangeToVisible:self.textView.selectedRange];
            }
            
        }else{
            if (trange.location!=NSNotFound) {
                
                NSInteger stringLength = self.textView.text.length;
                
                if (trange.location == stringLength) {
                    
                    [inputString appendString:text];
                }else{
                    [inputString insertString:text atIndex:trange.location];
                }
                self.textView.text = inputString;
                if (self.textView.selectedRange.location != (trange.location + text.length)) {
                    self.textView.selectedRange = NSMakeRange(trange.location + text.length, 0);
                    // added by tencent:jiachunke(20141127)
                    [self.textView scrollRangeToVisible:self.textView.selectedRange];
                }
            }
        }
        
        // modified by tencent:jiachunke(20141127)
        //[self textViewDidChange:self.textView];
        [self performSelector:@selector(textViewDidChange:) withObject:self.textView];
    }
}

- (NSRange)nsrangeInTextRange:(UITextRange *)range
{
    UITextPosition* beginning = self.textView.beginningOfDocument;
    
    UITextPosition* selectionStart = range.start;
    UITextPosition* selectionEnd = range.end;
    
    const NSInteger location = [self.textView offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [self.textView offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

#pragma mark - QLFaceKeyBoardDelegate

- (void)keyBoardDidPressSendButton{
    [self didPressSendButtonAction:nil];
}

- (void)showSystemBoardInTextView:(QLMomentTextView *)textV{
    _faceSendButton.hidden = NO;
    _keyboardButton.hidden = YES;
    _isSwitchingKeyBoard = YES;
    [self showSystemKeyBoard];
}

#pragma mark - Other
- (void)textViewScrollToVisibel:(int)numOfLines
{
    if (5 <= numOfLines)    //大于5行则可以滚动
    {
        _textView.scrollEnabled = YES;
        if (!_isShouldChangeFlag)
            [_textView scrollRangeToVisible:_textView.selectedRange];
    }
    else
    {
       // _textView.scrollEnabled = NO;
    }
}

#pragma mark-loginState
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
   if( [keyPath isEqualToString:@"frame"] && [object isEqual:[VPCommentInputBar sharedInstance]])
    {
        NSValue *newValue = [change objectForKey:NSKeyValueChangeNewKey];
        NSValue *oldvalue = [change objectForKey:NSKeyValueChangeOldKey];
        if ( [newValue CGRectValue].origin.y!= [oldvalue CGRectValue].origin.y)
        {
            if ([VPCommentInputBar isShowed]) {
                if (_delegate && [_delegate respondsToSelector:@selector(commentInputBarDidChangeHeight:)]) {
                    [_delegate commentInputBarDidChangeHeight:self];
                }
            }
        }
    }
}
@end
